<template>

	<view class="DetailView">
		<view class="content">
			<z-paging ref="paging" :refresher-only="true" :fixed="true" :show-loading-more-no-more-view='false'
				:refresher-enabled="false" :refresher-threshold="0" hide-refresher-when-reload
				hide-refresher-when-enabled>
				<template #top>
					<m-drag-button :style="{ opacity: BtnShow ? 1 : 0, }" :isDock="true" :existTabBar="true"
						:initialBottom="160" @btnClick="scan" :disabled='!buttonShow'>
						<template #BtnContent>
							<u-icon name="scan" color="#fff" size="54rpx"></u-icon>
						</template>
					</m-drag-button>
					<u-navbar :fixed="false" title="模具报废" :autoBack="true" :safeAreaInsetTop="true"
						@leftClick='leftClick' leftIconColor="#fff"></u-navbar>
				</template>

				<view class="MainBox">
					<u--form labelPosition="left" :model="baseFormData" :rules="rules" ref="uForm">

						<u-collapse v-if="collapseitem !== ''" :value="activeNames" :key="collapseitem">
							<u-collapse-item name="1" title="基本信息">

								<u-form-item labelWidth="100" label="单据编号" borderBottom leftIcon="order"
									:leftIconStyle="{'font-size':'20px'}">
									<u--input v-model="baseFormData.BillNO" placeholder="自动生成" readonly
										border="none"></u--input>
								</u-form-item>
								<u-form-item labelWidth="100" label="单据日期" borderBottom leftIcon="calendar"
									:borderBottom='EnableApplyForShow' prop="BillDate"
									:leftIconStyle="{'font-size':'20px'}">
									<u--input v-model="baseFormData.BillDate" placeholder="自动生成" readonly
										border="none"></u--input>
								</u-form-item>
								<u-form-item labelWidth="100" label="申请人" borderBottom leftIcon="order"
									v-show="EnableApplyForShow" :leftIconStyle="{'font-size':'20px'}">
									<u--input v-model="baseFormData.ApplicantName" placeholder="自动生成" readonly
										border="none"></u--input>
								</u-form-item>
								<u-form-item labelWidth="100" label="申请时间" borderBottom leftIcon="calendar"
									v-show="EnableApplyForShow" prop="ApplicationTime"
									:leftIconStyle="{'font-size':'20px'}">
									<u--input v-model="baseFormData.ApplicationTime" placeholder="自动带出申请时间" readonly
										border="none"></u--input>
								</u-form-item>

								<u-form-item labelWidth="100" label="申请状态" borderBottom leftIcon="order"
									v-show="EnableApplyForShow" :leftIconStyle="{'font-size':'20px'}">
									<u--input v-model="baseFormData.ApplicationStatusName" placeholder="自动带出申请状态"
										border="none" readonly></u--input>
								</u-form-item>
								<u-form-item labelWidth="100" label="申请结果" borderBottom leftIcon="file-text"
									v-show="EnableApplyForShow" :leftIconStyle="{'font-size':'20px'}">
									<u--input v-model="baseFormData.ApplicationResultName" border="none" readonly
										placeholder="自动带出申请结果"></u--input>

								</u-form-item>
								<u-form-item labelWidth="100" label="确认人" borderBottom leftIcon="file-text"
									v-show="EnableApplyForShow" :leftIconStyle="{'font-size':'20px'}">
									<u--input v-model="baseFormData.ConfirmName" placeholder="自动带出人员" readonly
										border="none"></u--input>
								</u-form-item>
								<u-form-item labelWidth="100" label="确认时间" leftIcon="calendar"
									v-show="EnableApplyForShow" :leftIconStyle="{'font-size':'20px'}">
									<u--input v-model="baseFormData.ConfirmTime" placeholder="自动带出确认时间" readonly
										border="none"></u--input>
								</u-form-item>

							</u-collapse-item>

							<u-collapse-item name="2" title="报废信息">

								<u-form-item labelWidth="100" label="报废状态" borderBottom leftIcon="order"
									:leftIconStyle="{'font-size':'20px'}">
									<u--input v-model="baseFormData.ScrapStatusName" placeholder="自动带出申请状态"
										border="none" readonly></u--input>
								</u-form-item>
								<u-form-item labelWidth="100" label="执行人" borderBottom leftIcon="file-text"
									:leftIconStyle="{'font-size':'20px'}">
									<u--input v-model="baseFormData.ExecutorName" placeholder="自动带出" readonly
										border="none"></u--input>
								</u-form-item>
								<u-form-item labelWidth="100" label="报废时间" leftIcon="file-text"
									:leftIconStyle="{'font-size':'20px'}">
									<u--input v-model="baseFormData.ScrapTime" placeholder="自动带出" readonly
										border="none"></u--input>
								</u-form-item>
							</u-collapse-item>

						</u-collapse>

						</u-collapse>

					</u--form>

					<view class="AddBottomBox">
						<view class="left-buttons">
							<button class="CancelBtn" :disabled='!buttonShow' size='mini'
								@click='goGonavigateTo("归还")'>去归还</button>
							<button class=" CancelBtn" :disabled='!buttonShow' size='mini'
								@click='goGonavigateTo("领用")'>去领用</button>
						</view>
						<button class=" CancelBtn" :disabled='!buttonShow' size='mini'
							@click="openBaseScreen('模具','check')">新增</button>
					</view>


					<scroll-view scroll-x="true" class="scroll-view-fileList">
						<table class="fixed-table">
							<thead>
								<tr>
									<th class="sticky-col" width="50px">操作</th>
									<th width="100px">编号</th>
									<th width="100px">名称</th>
									<th width="100px">规格</th>
									<th width="120px">报废原因</th>
								</tr>
							</thead>
							<tbody>
								<tr v-for="(item, index) in tableData" :key="index">

									<td class="sticky-col" width="50px">
										<uni-icons type="trash" size="30" @click="trash(index)"></uni-icons>
									</td>
									<td width="100px">
										<u--textarea v-model="item.MoludCode" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td width="100px">
										<u--textarea v-model="item.MoludName" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td width="100px">
										<u--textarea v-model="item.MoludSpec" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td width="120px">
										<u--textarea v-model="item.Reason" placeholder="请输入报废原因" border="none"
											:disabled='!buttonShow' autoHeight
											style="padding: 0;backgroundColor:#fff;"></u--textarea>
									</td>

								</tr>
							</tbody>
						</table>
					</scroll-view>

				</view>
				<template #bottom>
					<view class="BottomBox" :style="$utils.disposeSafeBottomFun()" v-show="!baseFormData.ScrapID">
						<button block @click="submit('保存')" style="width: 90%;margin: 0 auto !important;"
							class="content_bottom_primary_Btn">
							保存
						</button>
					</view>
					<view class="BottomBox safe_buttom" :style="$utils.disposeSafeBottomFun()"
						v-show="baseFormData.ScrapID&&buttonShow">
						<button v-if="buttonNum==0" class="CancelBtn" @click="submit('保存')">保存</button>
						<button v-if="buttonTitleNum==1&&ApproveBack('发起申请')" class="ComfirmBtn"
							@click='SubmitBtn(11,"发起申请")'>发起申请</button>
						<button v-if="buttonTitleNum==2&&ApproveBack('撤回申请')" class="ComfirmBtn"
							@click='SubmitBtn(12,"撤回申请")'>撤回申请</button>
						<button v-if="buttonTitleNum==2&&ApproveBack('通过申请')" class="ComfirmBtn"
							@click='SubmitBtn(13,"通过申请")'>通过申请</button>
						<button v-if="buttonTitleNum==2&&ApproveBack('拒绝申请')" class="ComfirmBtn"
							@click='SubmitBtn(14,"拒绝申请")'>拒绝申请</button>
						<button v-if="scrapbutton&&ApproveBack('报废')" class="ComfirmBtn"
							@click='SubmitBtn(21,"报废")'>报废</button>

					</view>
				</template>
			</z-paging>
		</view>
		<u-toast ref="uToast"></u-toast>
		<u-modal :show="modalshow" :title="modaltitle" :content="modalcontent" :showCancelButton='true'
			@confirm='modalconfirm' @cancel='modalshow=false'>
		</u-modal>
		<m-pda-scancode v-if="$utils.isPda()" listenName="BatchEditScan"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>

	</view>

</template>

<script>
	import {
		formatDateTime,
		getTimeStamp,
		getFormatDate,
		getFormatDateTime,
		getBefore7DateTime
	} from '@/st_mold/common/base.js';
	import BaseMixin from '@/st_mold/common/base.js';
	export default {
		mixins: [BaseMixin],
		data() {
			return {
				rules: {
					'BillDate': {
						type: 'string',
						required: true,
						message: '单据日期不能为空',
						trigger: ['change']
					}
				},

				baseFormData: {
					ProcessNode: 0,
					ScrapID: 0,
					EmplID: null,
					BillDate: '',

					FType: 'BF',
					MoludID: null,
					MoludName: '',
					ApplicantName: '',
					ConfirmName: '',
					ConfirmTime: '',
					ScrapTime: '',
					ApplicationResult: null,
					ApplicationResultName: '',
					ApplicationStatusName: '',
					ApplicationStatus: null,
					ScrapStatus: null,
					ScrapStatusName: ''
				},
				buttonShow: true, //按钮是否隐藏
				buttonTitle: '保存', //按钮名称
				buttonNum: 0, //保存按钮值 等于0的时候显示
				buttonTitleNum: 0, //判断审核按钮值
				tableData: [], //子表数组
				scrapbutton: false, //报废按钮是否显示
				LYGHWSList: [], //警告信息列表
				MJBFSQRList: [], // 报废申请结果列表
				MJBFSList: [], // 报废状态列表
				MJBFSQList: [], //报废申请确认状态列表
				MJZTList: [], //模具状态列表
				collapseitem: '', //是否显示
				disabled: false, //按钮禁用
				trashIndex: null, //删除索引
				modalshow: false, //模态框
				modaltitle: '', //模态框提示语
				modalcontent: '', //模态框提示语
				BtnApprove: [], //权限判断
				EnableApplyForShow: false, //判断详情页面EnableApplyFor是否等于1
				EnableApplyForNum: null, //EnableApplyFor值
				BtnShow: false,
			};
		},
		onLoad(item) {
			var that = this
			let foundNode = null;

			for (const module of this.$store.state.appConfigInfo.ModuleInfo_All) {
				if (module.TreeTypeName === '模具管理') {
					for (const node of module.Node) {
						if (node.APFunName === '模具报废') {
							foundNode = JSON.parse(JSON.stringify(node));
							break; // 找到后立即退出内层循环  
						}
					}
					if (foundNode) {
						break;
					}
				}
			}

			this.BtnApprove = foundNode['IconApprove'];

			that.initData()

			// 判断是否有主键ID
			if (item.ScrapID) {
				that.queryList(item.ScrapID)
			} else {
				that.collapseitem = '1'
				that.baseFormData.EmplID = that.$store.state.UserInfo.EmplID
				that.baseFormData.BillDate = getFormatDate(new Date())
			}
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		onUnload() { // 监听页面卸载,
			// 关闭监听器
			uni.$off('BatchEditScan');
			uni.$off('st_moldScrapDetail');
		},
		mounted() {
			var that = this;

			setTimeout(() => {
				that.BtnShow = true;
			}, 300)
			// PDA扫码处理
			uni.$on('BatchEditScan', function(content) {
				let scanData = that.$utils.wmsFun.scanTransf(content);
				that.scanHandler(scanData);
			})
			uni.$on('st_moldScrapDetail', function(ret) {
				console.log(ret);
				if (ret.type == '模具') {
					ret.data.map(item => {
						item.WarningStatus = item.WarningStatus ? item.WarningStatus : 0
						item.WarningStatusName = item.WarningStatusName ? item.WarningStatusName : ''
						item.StockDeID = item.StockDeID ? item.StockDeID : 0
						item.Reason = item.Reason ? item.Reason : ''
					})
					that.tableData = [...that.tableData, ...ret.data]

				}
			});


		},
		computed: {
			activeNames() {
				if (this.collapseitem === '1') return ['1'];
				if (this.collapseitem === '2') return ['2'];
				if (this.collapseitem === '3') return ['1', '2'];
				return [];
			},

		},
		methods: {
			// pda扫码
			scanHandler(scanData) {
				let that = this;
				if (that.buttonShow) {
					that.MoludChange(scanData.recode, 'pda')
				}
			},
			// 手机扫描
			scan() {
				let that = this;
				if (that.buttonShow) {
					this.$scanPopup.openScan({
						success: function(res) {
							that.MoludChange(res.result, 'phone')
						},
						fail: function(fail) {
							console.log(fail);
						}
					})
				}

			},
			// 处理扫码数据
			MoludChange(res, name) {
				let that = this;
				let parts = res.split("|");
				console.log(parts);
				var id = parts[1]
				var obj = {}
				if (parts[0] == 'MJ') {
					obj.MoludID = id

				} else if (parts[0] == 'MJKW') {
					obj.FStorageID = id
				}
				console.log(obj);
				that.Request.request('MJ_MoludList', obj, (ret) => {
					console.log(ret);
					if (ret.data.ds1[0].status == 500) {
						uni.$u.toast(ret.data.ds1[0].msg)
					} else {
						ret.data.ds.map(obj => {
							obj.WarningStatus = obj.WarningStatus ? obj.WarningStatus : 0
							obj.WarningStatusName = obj.WarningStatusName ? obj.WarningStatusName : ''
							obj.StockDeID = obj.StockDeID ? obj.StockDeID : 0
						})
						that.tableData = [...that.tableData, ...ret.data.ds]
					}
				})
			},

			async initData() {
				// 加载公共字典数据
				await this.loadCommonDictionaries([{
						type: 'ALL',
						key: 'MJZTList'
					},
					{
						type: 'MJBFSQR',
						key: 'MJBFSQRList'
					},
					{
						type: 'LYGHWS',
						key: 'LYGHWSList'
					},
					{
						type: 'MJBFSQ',
						key: 'MJBFSQList'
					},
					{
						type: 'MJBFS',
						key: 'MJBFSList'
					}
				]);


			},

			ApproveBack(str) {
				let that = this;
				let Type = false;
				if (that.BtnApprove.length) {
					Type = that.BtnApprove.some(item => {
						return item.MenuName == str
					})
				}
				return Type;
			},
			// 子表删除
			trash(index) {
				var that = this
				if (that.buttonShow) {
					that.trashIndex = index
					that.modaltitle = '提示'
					that.modalcontent = '是否删除第' + (index + 1) + '行'
					that.modalshow = true
					this.$forceUpdate()
				}

			},
			// 模态框关闭
			modalconfirm() {
				var that = this
				that.modalshow = false

				if (that.modaltitle == '提示') {
					that.tableData.splice(that.trashIndex, 1)
				}
			},
			// 路径跳转
			goGonavigateTo(str) {
				let that = this;
				if (that.buttonShow) {
					var url = `./collectionReturnDetail?tableData=${JSON.stringify(that.tableData)}`
					that.$store.state.CRaftModule.MesBasicInfo.WorkbenchesTitle = str
					if (that.disabled == false) {
						// 立即禁用点击
						that.disabled = true
						uni.navigateTo({
							url: url,
							animationType: 'slide-in-right', // 动画类型
							animationDuration: 300 // 动画时长
						});
						setTimeout(() => {
							that.disabled = false
						}, 2000)
					}

				}

			},

			SubmitBtn(num, str) { // 提交按钮
				let that = this;
				this.$refs.uForm.validate().then(res => {
					let obj = {
						EmplID: that.baseFormData.EmplID,
						Motion: num,
						ScrapID: that.baseFormData.ScrapID
					};
					console.log(obj)
					that.Request.request('MJ_BFSubmitNode', obj, function(ret) {
						console.log(ret)
						var ScrapID = ret.data.ds[0].ScrapID ? ret.data.ds[0].ScrapID : that
							.baseFormData.ScrapID
						if (ret.data.ds[0].status == 500) {
							uni.$u.toast(ret.data.ds[0].msg)
						} else {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: str + '成功'
							})
							that.queryList(ScrapID);
						}
					}, function(err) {
						console.log(err)
					})
				}).catch(errors => {
					console.log(JSON.stringify(errors))
					if (Array.isArray(errors)) {
						uni.$u.toast('请完善表单')
					}
				});
			},

			// 关闭弹框
			confirmClick() {
				this.popup_logout = false
			},
			// 展示控制面板
			collapseitemChange() {
				var that = this
				if (that.baseFormData.ProcessNode == 0) {
					that.collapseitem = '1'
				} else if (that.baseFormData.ProcessNode == 1) {
					that.collapseitem = '2'
				} else if (that.baseFormData.ProcessNode == 2) {
					that.collapseitem = '3'
				}
				that.$nextTick(() => {
					that.$forceUpdate()
				});
			},
			// 判断按钮显示条件
			addPeriodTypeClick() {
				var that = this
				that.collapseitemChange()

				if (that.EnableApplyForNum == 1) {

					if (that.baseFormData.ProcessNode != 2) {
						that.buttonNum = 0 //保存
						that.scrapbutton = true //报废按钮显示
					} else {
						that.buttonNum = null //保存隐藏
						that.buttonTitleNum = null //隐藏
						that.scrapbutton = false //报废按钮隐藏
						that.buttonShow = false //按钮隐藏
					}

				} else {
					if (that.baseFormData.ProcessNode == 0 && that.baseFormData.ApplicationStatus == 0 &&
						!that.baseFormData.ScrapID) {

						that.buttonNum = 0 //保存
						that.buttonTitleNum = 0 //保存
					} else if (that.baseFormData.ProcessNode == 0 && that.baseFormData.ApplicationStatus == 0 &&
						that.baseFormData.ScrapID) {
						that.buttonNum = 0 //保存
						that.buttonTitleNum = 1 //发起申请
					} else if (that.baseFormData.ProcessNode == 0 && that.baseFormData.ApplicationStatus == 1) {
						that.buttonNum = null //保存隐藏
						that.buttonTitleNum = 2 //撤回
					} else if (that.baseFormData.ProcessNode == 1 && that.baseFormData.ScrapStatus == 0) {
						that.buttonNum = null //保存隐藏
						that.buttonTitleNum = null //报废按钮显示
						that.scrapbutton = true //报废按钮显示
					} else {
						that.buttonNum = null //保存隐藏
						that.buttonTitleNum = null //隐藏
						that.scrapbutton = false //报废按钮隐藏
						that.buttonShow = false //按钮隐藏
					}
				}

				that.$forceUpdate()
			},


			openBaseScreen(str, type) { // 前往筛选页
				let that = this;
				let obj = null;
				// let url = '/commonPage/Tool/baseScreen'; //单选
				var url = '/commonPage/Tool/SelectBaseScreen'; //多选
				if (that.buttonShow) {
					if (str == '模具') {
						obj = {
							allowClear: false,
							cmd: 'MJ_MoludList',
							type: str,
							ListeningName: 'st_moldScrapDetail',
							serverSearch: {
								isPaging: false, //是否分页
								searchKey: 'MoludSelect', //搜索关键词，应包含在param中
								showText: 'MoludSelect', //查询结果显示的字段
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								// ChoiceDataKey: 'MoludName',  //选中的值
								// ChoiceDataData: that.baseFormData.MoludName,
							},
							param: {
								FType: 'BF',
								MoludSelect: '',
								PageIndex: 1,
								PageSize: 30,
								IsInStorage: -1
							}
						}
					}
					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: obj
					})
					uni.navigateTo({
						url: url
					})
				}
			},

			// 保存
			submit(str) {
				var that = this
				var show = true
				var msg
				if (that.tableData.length == 0) {
					show = false
					msg = '请新增模具'
				}
				that.tableData.forEach((item, index) => {
					if (item.ScrapDeID == '' || item.ScrapDeID == null || item.ScrapDeID == undefined) {
						item.ScrapDeID = 0
					}
					if (item.Reason == '' || item.Reason == null || item.Reason == undefined) {
						show = false
						msg = '请输入第' + (index + 1) + '行报废原因'
					}
				})

				if (show) {
					this.$refs.uForm.validate().then(res => {
						let obj = {

							BillDate: that.baseFormData.BillDate,
							EmplID: that.baseFormData.EmplID,
							FType: 'BF',
							ScrapID: that.baseFormData.ScrapID,
							Reason: that.tableData.map(item => item.Reason).join(','),
							ScrapDeID: that.tableData.map(item => item.ScrapDeID).join(','),
							MoludID: that.tableData.map(item => item.MoludID).join(',')
						};
						console.log(obj)
						that.Request.request('MJ_BFSubmit', obj, function(ret) {
							console.log(ret)
							var ScrapID = ret.data.ds[0].ScrapID
							if (ret.data.ds[0].status == 500) {
								uni.$u.toast(ret.data.ds[0].msg)
							} else {
								that.$refs.uToast.show({
									title: '保存',
									type: 'success',
									message: '保存成功'
								})
								that.queryList(ScrapID);
							}
						}, function(err) {
							console.log(err)

						})
					}).catch(errors => {
						console.log(JSON.stringify(errors))
						if (Array.isArray(errors)) {
							uni.$u.toast('请完善表单')
						}
					});
				} else {
					that.modaltitle = '提醒'
					that.modalshow = true
					that.modalcontent = msg
				}
			},
			// 详情数据
			queryList(id) {
				var that = this
				that.loading = true
				try {
					that.Request.request('MJ_BFDetail', {
						ScrapID: id
					}, (ret) => {
						console.log(ret.data);
						that.loading = false
						ret.data.ds.map((item) => {
							item.EmplID = item.EmplID ? item.EmplID : that.$store
								.state.UserInfo.EmplID
							item.CloseStatus = item.CloseStatus ? item.CloseStatus : 0
							item.CKTime = formatDateTime(item.CKTime)
							item.BillDate = formatDateTime(item.BillDate)
							item.ApplicationTime = formatDateTime(item.ApplicationTime)
							item.ConfirmTime = formatDateTime(item.ConfirmTime)
							item.ScrapTime = formatDateTime(item.ScrapTime)

							const dictMappings = {
								ApplicationStatus: {
									dictKey: 'MJBFSQ',
									targetField: 'ApplicationStatusName'
								},
								ApplicationResult: {
									dictKey: 'MJBFSQR',
									targetField: 'ApplicationResultName'
								},
								ScrapStatus: {
									dictKey: 'MJBFS',
									targetField: 'ScrapStatusName'
								}
							};
							that.mapDictNamesForItem(item, dictMappings);

						})
						ret.data.ds1.map((item) => {
							item.WarningStatus = item.WarningStatus ? item.WarningStatus : 0
							const dictMappings = {
								WarningStatus: {
									dictKey: 'LYGHWS',
									targetField: 'WarningStatusName'
								}
							};

							that.mapDictNamesForItem(item, dictMappings);
						})
						that.baseFormData = ret.data.ds[0]
						that.tableData = ret.data.ds1
						that.addPeriodTypeClick()
						that.$forceUpdate()

					})
				} catch (e) {
					that.loading = false
					console.log(e)
					this.$utils.msg('请求失败请重试')
				}
			},
			// 退出	
			leftClick() {
				let routes = getCurrentPages(); //当前页面栈
				let prevPage = routes[routes.length - 2]
				prevPage.$vm.getList()
			}
		}
	}
</script>

<style lang="scss">
	@import "./css/index.scss";

	.scroll-view-fileList {
		margin-bottom: 20px;
	}

	.u-collapse-item__content__text {
		padding: 0 !important;
		margin: 0 !important;
	}

	.content {
		.BottomBox {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding: 10px 10px;

			.CancelBtn {
				background-color: #fff;
				color: #51d0d0;
				border: 1px solid #51d0d0;
				min-width: 60px;
			}

			.ComfirmBtn {
				background-color: #51d0d0;
				color: #fff;
				min-width: 60px;
				margin-left: 10px !important;
			}
		}
	}

	.AddBottomBox {
		justify-content: space-between;
	}
</style>